<template>
  <div class="import-operation">
    <el-button type="primary" icon="el-icon-upload" @click="handleOpenDialog">
      <slot />
    </el-button>
    <el-dialog :visible.sync="show" :title="dialogTitle" :close-on-click-modal="false" width="50%"
      @close="closeDialog" custom-class="import-operation__dialog">
      <slot name="tips" />
      <div v-if="isShowUpload" class="import-operation__upload-warp">
        <el-upload ref="elUploadRef" class="upload-demo" accept=".xls,.xlsx" :limit="1" drag :http-request="onUploadEvent"
          :on-exceed="onExceed" action="">
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-button type="text" @click="handleDownLoadSampleFile">下载示例文件</el-button>
      </div>
      <div v-else class="import-operation__topicList">
        <el-form :inline="true">
          <el-form-item>
            <el-button @click="reset">重新选择文件</el-button>
            <el-button v-if="isShowPaper" @click="modifyPaper">修改试卷名称</el-button>
            <el-button type="primary" @click="sumbit">提交</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="topicTabel" style="width: 100%" border>
          <el-table-column align="center" prop="topic" label="题目" width="240">
            <template slot-scope="scope">
              <template v-if="scope.row.editable">
                <el-input v-model="scope.row.topic" />
              </template>
              <template v-else>{{ scope.row.topic }}</template>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="option" label="选项" width="240">
            <template slot-scope="scope">
              <template v-if="scope.row.editable">
                <el-input type="textarea" :rows="2" v-model="scope.row.option" />
              </template>
              <template v-else>{{ scope.row.option }}</template>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="answer" label="答案" width="160">
            <template slot-scope="scope">
              <template v-if="scope.row.editable">
                <el-input v-model="scope.row.answer" />
              </template>
              <template v-else>{{ scope.row.answer }}</template>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="type" label="类型" width="120">
            <template slot-scope="scope">
              <template v-if="scope.row.editable">
                <el-select :value="getValue(scope.row.type)" placeholder="请选择题目类型" 
                @input="setValue(scope.row,'type',typeOptions,$event)">
                  <el-option v-for="option in typeOptions" :key="option.value" :label="option.label"
                    :value="option.value" />
                </el-select>
              </template>
              <template v-else>{{ scope.row.type.label }}</template>
            </template>
          </el-table-column>

          <el-table-column align="center" fixed="right" label="操作" width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.editable">
                <el-button type="primary" plain size="mini" @click="saveRow(scope.row)">
                保存
              </el-button>
              </div>
              <div v-else>
                <el-button style="margin-right: 20px;" type="primary" icon="el-icon-edit" circle @click="editRow(scope.row)"/>
                <el-button type="danger" @click="delRow(scope.$index)" icon="el-icon-delete" circle/>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="isShowPaperDialog" title="修改试卷信息" :close-on-click-modal="false" width="600px">
      <div class="import-operation-paperinfo">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px">
          <el-form-item label="试卷名称" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="及格百分比率" prop="percentage">
            <el-input v-model="ruleForm.percentage"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'ImportOperation',
  props: {
    dialogTitle: {
      type: String,
      default: '导入'
    },
    sampleFileDownLoadAddr: {
      type: String,
      default: ''
    },
    topicTabel: {
      type: Array,
      default: () => []
    },
    isShowPaper:{
      type:Boolean,
      default:false
    },
    title:{
      type:String,
      default:'导入试卷'
    },
    percentage:{
      type:String,
      default:'60'
    }
  },
  data() {
    return {
      show: false,
      isShowUpload: true,
      isShowPaperDialog:false,
      topicDate:[],
      count:'',
      typeOptions: [
        { label: '单选', value: 1 },
        { label: '多选', value: 2 },
        { label: '判断', value: 3 },
      ],
      pagination: {
        current: 1,
        size: 10
      },
      ruleForm:{
        title:'',
        percentage:'',
      },
      rules:{
        title:[
          { required: true, message: '请输入试卷名称', trigger: 'blur' },
        ],
        percentage:[
          { required: true, message: '请输入及格百分比率', trigger: 'blur' },
        ]
      }
    }
  },
  methods: {

    handleOpenDialog() {
      this.show = true
    },

    onExceed() {
      this.$message.error('超过最大可上传数量，请移除已上传的文件后继续操作！')
    },

    onUploadEvent(e) {
      // const formData = new FormData()
      // formData.append('file', e.file)
      this.$emit('uploadSuccess', e)
    },

    handleDownLoadSampleFile() {
      window.open(this.sampleFileDownLoadAddr)
    },

    clearUploadedFiles() {
      this.$refs.elUploadRef.clearFiles()
    },

    defaultFormatter(){
     
    },
    reset() {
      this.isShowUpload = true
    },
    getValue(obj) {
      return obj.value
    },
    setValue(obj, key, options, value) {
      const option = options.find(item => item.value === value)
      obj[key] = option
    },
    saveRow(row){
      this.$set(row, 'editable', false)
    },
    editRow(row){
      console.log(row,'row');
      this.$set(row, 'editable', true)
    },
    async delRow(index){
      try {
        await this.$confirm('提示','您确定要删除这条数据吗?')
        const { current, size } = this.pagination
        const offset = (current * size) - size
        this.topicTabel.splice(offset + index, 1)
      } catch (error) {
        console.log(error);
        this.$message.error('删除失败')
      }
    },
    async sumbit(){
      console.log(this.topicTabel,'topicTabel');
      const newData = this.topicTabel.map(item=>{
        return {
          ...item,
          type:item.type.value
        }
      })
      if (newData.length<=0) {
          this.$message.error("没有数据可添加")
          return
        }
        
        const jsonData = JSON.stringify(newData)
        const formData = new FormData()
        formData.append('data', jsonData)
        if (this.isShowPaper) {
          const params={
            data:jsonData,
            title:this.ruleForm.title,
            percentage:this.ruleForm.percentage
          }
          this.$emit('handleSumbits',params)
        }else{
          this.$emit('handleSumbits',formData)
        }
        
    },
    modifyPaper(){
        if (this.count !==0) {
          console.log('进来了');
          this.ruleForm.title=this.title
          this.ruleForm.percentage=this.percentage
          this.count=0
        }
        this.isShowPaperDialog=true
    },
    closeDialog(){
      this.isShowUpload=true
    },
    submitForm(formName){
      this.$refs[formName].validate((valid)=>{
        if (valid) {
          this.isShowPaperDialog=false
        }
      })
    }
  },
}
</script>
<style lang="scss" scoped>
.import-operation {
  margin: 0 10px;

  &__upload-warp {
    padding: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  &__topicList {
    padding: 10px 20px;
  }
}

:deep(.import-operation__dialog) {
  .el-dialog__body {
    padding: 0;
  }
}
</style>
